package com.chenyi.system.service.impl;

import com.chenyi.common.core.redis.RedisCache;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.system.domain.SysAdminPostAccess;
import com.chenyi.system.domain.SysAdminRoleAccess;
import com.chenyi.system.service.ISysAdminService;
import com.chenyi.common.annotation.AdminDataScope;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.domain.entity.SysAdminRole;
import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.system.domain.SysAdminPost;
import com.chenyi.system.mapper.*;
import com.chenyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户 业务层处理
 * 
 * @author wangkh
 */
@Service
public class SysAdminServiceImpl implements ISysAdminService
{
    private static final Logger log = LoggerFactory.getLogger(SysAdminServiceImpl.class);

    @Autowired
    private SysAdminMapper adminMapper;

    @Autowired
    private SysAdminRoleMapper adminRoleMapper;

    @Autowired
    private SysAdminPostMapper adminPostMapper;

    @Autowired
    private SysAdminRoleAccessMapper adminRoleAccessMapper;

    @Autowired
    private SysAdminPostAccessMapper adminPostAccessMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;
    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
        String adminNo = adminMapper.selectFinallyAdminNo();
        redisCache.setCacheObject("sys_no:admin_no",adminNo);
    }


    /**
     * 根据条件分页查询用户列表
     * 
     * @param admin 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @AdminDataScope(deptAlias = "d", userAlias = "u")
    public List<SysAdmin> selectAdminList(SysAdmin admin)
    {
        return adminMapper.selectAdminList(admin);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysAdmin selectAdminByUserName(String userName)
    {
        return adminMapper.selectAdminByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysAdmin selectAdminById(Long userId)
    {
        return adminMapper.selectAdminById(userId);
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectAdminRoleGroup(String userName)
    {
        List<SysAdminRole> list = adminRoleMapper.selectAdminRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysAdminRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectAdminPostGroup(String userName)
    {
        List<SysAdminPost> list = adminPostMapper.selectAdminPostByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysAdminPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = adminMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param admin 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysAdmin admin)
    {
        Long userId = StringUtils.isNull(admin.getAdminId()) ? -1L : admin.getAdminId();
        SysAdmin info = adminMapper.checkPhoneUnique(admin.getPhone());
        if (StringUtils.isNotNull(info) && info.getAdminId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param admin 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysAdmin admin)
    {
        Long userId = StringUtils.isNull(admin.getAdminId()) ? -1L : admin.getAdminId();
        SysAdmin info = adminMapper.checkEmailUnique(admin.getEmail());
        if (StringUtils.isNotNull(info) && info.getAdminId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param admin 用户信息
     */
    @Override
    public void checkAdminAllowed(SysAdmin admin)
    {
        if (StringUtils.isNotNull(admin.getAdminId()) && admin.isAdmin())
        {
            throw new MessageException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param admin 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAdmin(SysAdmin admin)
    {
        admin.setAdminNo(getAdminNo());
        // 新增用户信息
        int rows = adminMapper.insertAdmin(admin);
        // 新增用户岗位关联
        insertAdminPost(admin);
        // 新增用户与角色管理
        insertAdminRole(admin);
        return rows;
    }

    /**
     * 修改保存用户信息
     * 
     * @param admin 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAdmin(SysAdmin admin)
    {
        Long adminId = admin.getAdminId();
        // 删除用户与角色关联
        adminRoleAccessMapper.deleteUserRoleByUserId(adminId);
        // 新增用户与角色管理
        insertAdminRole(admin);
        // 删除用户与岗位关联
        adminPostAccessMapper.deleteAdminPostByAdminId(adminId);
        // 新增用户与岗位管理
        insertAdminPost(admin);
        return adminMapper.updateAdmin(admin);
    }

    /**
     * 修改用户状态
     * 
     * @param admin 用户信息
     * @return 结果
     */
    @Override
    public int updateAdminStatus(SysAdmin admin)
    {
        return adminMapper.updateAdmin(admin);
    }

    /**
     * 修改用户基本信息
     * 
     * @param admin 用户信息
     * @return 结果
     */
    @Override
    public int updateAdminProfile(SysAdmin admin)
    {
        return adminMapper.updateAdmin(admin);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateAdminAvatar(String userName, String avatar)
    {
        return adminMapper.updateAdminAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param admin 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysAdmin admin)
    {
        return adminMapper.updateAdmin(admin);
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetAdminPwd(String userName, String password)
    {
        return adminMapper.resetAdminPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     * 
     * @param admin 用户对象
     */
    public void insertAdminRole(SysAdmin admin)
    {
        Long[] roles = admin.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysAdminRoleAccess> list = new ArrayList<SysAdminRoleAccess>();
            for (Long roleId : roles)
            {
                SysAdminRoleAccess ur = new SysAdminRoleAccess();
                ur.setAdminId(admin.getAdminId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                adminRoleAccessMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     * 
     * @param admin 用户对象
     */
    public void insertAdminPost(SysAdmin admin)
    {
        Long[] posts = admin.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysAdminPostAccess> list = new ArrayList<SysAdminPostAccess>();
            for (Long postId : posts)
            {
                SysAdminPostAccess up = new SysAdminPostAccess();
                up.setAdminId(admin.getAdminId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                adminPostAccessMapper.batchAdminPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param adminId 用户ID
     * @return 结果
     */
    @Override
    public int deleteAdminById(Long adminId)
    {
        // 删除用户与角色关联
        adminRoleAccessMapper.deleteUserRoleByUserId(adminId);
        // 删除用户与岗位表
        adminPostAccessMapper.deleteAdminPostByAdminId(adminId);
        return adminMapper.deleteAdminById(adminId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param adminIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteAdminByIds(Long[] adminIds)
    {
        for (Long userId : adminIds)
        {
            checkAdminAllowed(new SysAdmin(userId));
        }
        return adminMapper.deleteAdminByIds(adminIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importAdmin(List<SysAdmin> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new MessageException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.admin.initPassword");
        for (SysAdmin admin : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysAdmin u = adminMapper.selectAdminByUserName(admin.getUserName());
                if (StringUtils.isNull(u))
                {
                    admin.setPassword(AdminUtils.encryptPassword(password));
                    admin.setCreateBy(operName);
                    this.insertAdmin(admin);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + admin.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    admin.setUpdateBy(operName);
                    this.updateAdmin(admin);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + admin.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + admin.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + admin.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BadRequestException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    /* 功能描述: <br>
     * 〈获取商户编号〉
     *
     * @param
     * @return: java.lang.String
     * @Author: wangkh
     * @Date: 2020/11/2 0002 15:29
     */
    private String getAdminNo(){
        String sysNo = redisCache.getCacheObject("sys_no:admin_no");
        String prefix = sysNo.substring(0,2);
        Integer adminNo = Integer.parseInt(sysNo.substring(2)) + 1;
        return prefix + adminNo;
    }
}
